import { Space } from 'antd'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import PageComponent from './PageComponent'
import './index.scss'

const birthday = "10-15"

const CountdownTimer: React.FC = () => {
  const [dayNumber, setDayNumber] = useState(0)
  const [hourNumber, setHourNumber] = useState(0)
  const [minuteNumber, setMinuteNumber] = useState(0)
  const [secondNumber, setSecondNumber] = useState(0)

  useEffect(() => {
    let year = dayjs().year()
    if (new Date() > new Date(`${year}-${birthday}`)) {
      year++
    }
    const DATE = `${year}-${birthday}`
    
    let grossSecond = dayjs(DATE).diff(dayjs(), 's')
    let days = 0
    let hours = 0
    let minutes = 0
    let seconds = 0
    days = Math.floor(grossSecond / (3600 * 24))
    grossSecond = grossSecond - days * 3600 * 24
    hours = Math.floor(grossSecond / 3600)
    grossSecond = grossSecond - hours * 3600
    minutes = Math.floor(grossSecond / 60)
    grossSecond = grossSecond - minutes * 60
    seconds = grossSecond
    setDayNumber(days)
    setHourNumber(hours)
    setMinuteNumber(minutes)
    setSecondNumber(seconds)
    const timer = setInterval(() => {
      let grossSecond = dayjs(DATE).diff(dayjs(), 's')
      days = Math.floor(grossSecond / (3600 * 24))
      grossSecond = grossSecond - days * 3600 * 24
      hours = Math.floor(grossSecond / 3600)
      grossSecond = grossSecond - hours * 3600
      minutes = Math.floor(grossSecond / 60)
      grossSecond = grossSecond - minutes * 60
      seconds = grossSecond
      setDayNumber(days)
      setHourNumber(hours)
      setMinuteNumber(minutes)
      setSecondNumber(seconds)
    }, 1000)

    return () => {
      timer && clearInterval(timer)
    }
  }, [])


  return (
    <div className='page-body'>
      <div className='calendar'>
        <div className='title'>距离xxx下一次生日还剩下</div>
        <Space size={80}>
          <div>
            <PageComponent number={dayNumber} />
            <div className='unit'>天</div>
          </div>
          <div>
            <PageComponent number={hourNumber} />
            <div className='unit'>小时</div>
          </div>
          <div>
            <PageComponent number={minuteNumber} />
            <div className='unit'>分钟</div>
          </div>
          <div>
            <PageComponent number={secondNumber} />
            <div className='unit'>秒</div>
          </div>
        </Space>
      </div>
    </div>
  )
}

export default CountdownTimer